<?php

namespace app\adminapi\controller;

use app\common\controller\Captcha;
use app\common\controller\Captcode;
use think\facade\Cache;
use think\facade\Db;
use app\api\model\User;
use app\BaseController;
use Firebase\JWT\JWT;
use think\App;
use think\exception\HttpResponseException;


/**
 * 登录控制器
 */
class Login extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);


        $config = [
            'app_id' => 'wx7a754d5410f8edfe',
            'secret' => 'd01a9640aa69b3ade7af3cfbd4f8ea8d',
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

    }


    public function login()
    {
        $data = $this->_vali([
            'username.min:4'   => '登录账号不能少于4位字符!',
            'password.require' => '登录密码不能为空!',
            'password.min:4'   => '登录密码不能少于4位字符!',
            'code.require'   => '验证码不能为空',
            'codeidenty.require'   => '验证码不能为空',
        ],"POST");

        // 验证码
        $captcha = new Captcode();
        $cks = $captcha->check($data['code'],$data['codeidenty']);
        if(!$cks['code']){
            return json($cks);
        }

        if (!$user = Db::name('system_user')->where('username',$data['username'])->where('status',1)->field('id,username,password')->find()) {
            return json(['code'=>0,'msg'=>'账号不存在或不可登录']);
        }

        if ($user['password'] != md5($data['password'])) {
            return json(['code'=>0,'msg'=>'密码错误']);
        }
        unset($user['password']);

        // 验证token
        $time = time();
        $token = [
            'iat' => $time, //签发时间
            'nbf' => $time , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => time() + 3600 * 24 * 14, //过期时间
            'data' => [ //自定义信息，不要定义敏感信息
                'user_id' => $user['id'],
                'username' => $user['username'],
            ]
        ];

        $user['exp'] = $token['exp'];
        $user['token'] = JWT::encode($token,"pms");
        return json(['status'=>200,'msg'=>'登录成功','data'=>$user]);
    }


    public function code()
    {
        $code = new Captcode();
        $generator = $code->generate();
        $capt = new Captcha();
        $image = $capt->create($generator);

        Cache::set($generator['key'],$generator['value'],600);
        return json([
            'code'=>1,
            'key'=>$image['key'],
            'image'=>$image['image'],
            'value'=>$generator['value']
        ]);
    }
}